
// pages/Face/Face.js
const BAIDU_API_KEY = 'DAsghNV72aPt0IRmVngyRviI';
const BAIDU_SECRET_KEY = 'R55xRZaXUCCGFXVlVa40lMDUZ5FMzJbE';
const BAIDU_FACE_URL = 'https://aip.baidubce.com/rest/2.0/face/v3/detect';

Page({
  data: {
    imagePath: '',
    result: null,
    loading: false
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: (res) => {
        this.setData({ imagePath: res.tempFilePaths[0] });
        this.detectFace(res.tempFilePaths[0]);
      }
    });
  },

  // 拍照
  takePhoto() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: (res) => {
        this.setData({ imagePath: res.tempFilePaths[0] });
        this.detectFace(res.tempFilePaths[0]);
      }
    });
  },

  // 获取百度API访问令牌
  getAccessToken() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://aip.baidubce.com/oauth/2.0/token',
        method: 'POST',
        data: {
          grant_type: 'client_credentials',
          client_id: BAIDU_API_KEY,
          client_secret: BAIDU_SECRET_KEY
        },
        success: (res) => {
          if (res.data.access_token) {
            resolve(res.data.access_token);
          } else {
            reject(new Error('获取access_token失败'));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  // 调用百度人脸识别API
  async detectFace(filePath) {
    this.setData({ loading: true, result: null });
    
    try {
      const accessToken = await this.getAccessToken();
      const base64 = await this.getFileBase64(filePath);
      
      wx.request({
        url: `${BAIDU_FACE_URL}?access_token=${accessToken}`,
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: {
          image: base64,
          image_type: 'BASE64',
          face_field: 'age,gender,beauty,expression,face_shape,glasses,emotion,face_type'
        },
        success: (res) => {
          if (res.data.error_code) {
            wx.showToast({
              title: `识别失败: ${res.data.error_msg}`,
              icon: 'none'
            });
          } else {
            this.processResult(res.data.result);
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '请求失败，请重试',
            icon: 'none'
          });
        },
        complete: () => {
          this.setData({ loading: false });
        }
      });
    } catch (err) {
      wx.showToast({
        title: err.message || '识别失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  // 获取文件的base64编码
  getFileBase64(filePath) {
    return new Promise((resolve, reject) => {
      wx.getFileSystemManager().readFile({
        filePath,
        encoding: 'base64',
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          reject(new Error('读取文件失败'));
        }
      });
    });
  },

  // 处理识别结果
  processResult(result) {
    console.log('API返回原始数据:', JSON.stringify(result));
    
    if (!result || !result.face_num || !result.face_list || result.face_list.length === 0) {
      wx.showToast({
        title: '未检测到人脸或数据格式错误',
        icon: 'none'
      });
      return;
    }

    try {
      const faceInfo = result.face_list[0];
      const processedResult = [];
      
      // 确保每个字段都存在再处理
      if (faceInfo.gender && faceInfo.gender.type) {
        processedResult.push({ 
          label: '性别', 
          value: faceInfo.gender.type === 'male' ? '男' : '女' 
        });
      }
      
      if (faceInfo.age) {
        processedResult.push({ label: '年龄', value: faceInfo.age });
      }
      
      if (faceInfo.beauty) {
        processedResult.push({ label: '颜值', value: faceInfo.beauty });
      }
      
      if (faceInfo.expression && faceInfo.expression.type) {
        processedResult.push({ 
          label: '表情', 
          value: faceInfo.expression.type === 'none' ? '无表情' : faceInfo.expression.type 
        });
      }
      
      if (faceInfo.face_shape && faceInfo.face_shape.type) {
        processedResult.push({ label: '脸型', value: faceInfo.face_shape.type });
      }
      
      if (faceInfo.glasses && faceInfo.glasses.type) {
        processedResult.push({ 
          label: '眼镜', 
          value: faceInfo.glasses.type === 'none' ? '无眼镜' : faceInfo.glasses.type 
        });
      }
      
      if (faceInfo.emotion && faceInfo.emotion.type) {
        processedResult.push({ label: '情绪', value: faceInfo.emotion.type });
      }
      
      if (faceInfo.face_type && faceInfo.face_type.type) {
        processedResult.push({ 
          label: '人种', 
          value: faceInfo.face_type.type === 'human' ? '黄种人' : faceInfo.face_type.type 
        });
      }

      console.log('处理后的结果:', processedResult);
      this.setData({ result: processedResult });
      
    } catch (err) {
      console.error('处理结果出错:', err);
      wx.showToast({
        title: '处理识别结果出错',
        icon: 'none'
      });
    }
  },

  // 生命周期函数
  onLoad() {},
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
});